<template>
  <el-dialog
    title="执行计划"
    :model-value="visible"
    @update:model-value="emit('update:visible', $event)"
    width="80%"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    append-to-body
  >
    <div class="execution-plan-container">
      <div class="plan-section">
        <div class="section-title">生产管理/工序任务管理/生产执行</div>
        
        <div class="info-section">
          <div class="sub-section-title">工序信息</div>
          <div class="info-grid">
            <div class="info-row">
              <div class="info-item">
                <span class="info-label">任务编号：</span>
                <span class="info-value">{{ taskInfo.taskCode }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">生产批次号：</span>
                <span class="info-value">{{ taskInfo.batchCode }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">工序状态：</span>
                <span class="info-value">{{ taskInfo.taskStatus }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">任务优先级：</span>
                <span class="info-value">{{ taskInfo.taskPriority }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="info-section">
          <div class="sub-section-title">成品信息</div>
          <el-table :data="productList" border style="width: 100%">
            <el-table-column type="index" label="序号" width="70" align="center" />
            <el-table-column prop="productCode" label="成品编号" align="center" />
            <el-table-column prop="productName" label="成品名称" align="center" />
            <el-table-column prop="productType" label="成品类型" align="center">
              <!-- <template #default="scope">
                <template v-if="allDictionaries['Productgui']">
                  {{ getDictionaryText('Productgui', scope.row.productType) }}
                </template>
                <template v-else>
                  {{ scope.row.productType }}
                </template>
              </template> -->
            </el-table-column>
            <el-table-column prop="productCompany" label="所属公司" align="center">
              <template #default="scope">
                <template v-if="allDictionaries['Ware_ProductCompany']">
                  {{ getDictionaryText('Ware_ProductCompany', scope.row.productCompany) }}
                </template>
                <template v-else>
                  {{ scope.row.productCompany }}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="productType" label="规格型号" align="center" />
            <el-table-column prop="productCompany" label="单位" align="center" />
            <el-table-column prop="productBatch" label="批次号" align="center" />
            <el-table-column prop="productNumS" label="库存上限" align="center" />
            <el-table-column prop="productNumX" label="库存下限" align="center" />
            <!-- <el-table-column prop="planQuantity" label="计划数量" align="center" />
            <el-table-column prop="completedQuantity" label="已完成数量" align="center" />
            <el-table-column prop="defectQuantity" label="不良品数量" align="center" /> -->
            <el-table-column prop="status" label="状态" align="center">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  <template v-if="allDictionaries['Ware_ProductState']">
                    {{ getDictionaryText('Ware_ProductState', scope.row.status) }}
                  </template>
                  <template v-else>
                    {{ scope.row.status }}
                  </template>
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage1"
              v-model:page-size="pageSize1"
              :page-sizes="[10, 20, 30, 40]"
              layout="total, sizes, prev, pager, next"
              :total="totalItems1"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
        
        <div class="info-section">
          <div class="sub-section-title">报工记录</div>
          <el-table :data="workReportList" border style="width: 100%">
            <el-table-column type="index" label="序号" width="70" align="center" />
            <el-table-column prop="reportQty" label="报工数量" align="center" />
            <el-table-column prop="deviceName" label="设备名称" align="center" />
            <el-table-column prop="deviceCode" label="设备编号" align="center" />
            <el-table-column prop="operator" label="操作人" align="center" />
            <el-table-column prop="reportTime" label="报工时间" align="center" />
            <el-table-column prop="remark" label="备注" align="center" />
          </el-table>
          
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage2"
              v-model:page-size="pageSize2"
              :page-sizes="[10, 20, 30, 40]"
              layout="total, sizes, prev, pager, next"
              :total="totalItems2"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="startWork">报工</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import http from '@/api/http';

// 内部状态
const currentPage1 = ref(1);
const currentPage2 = ref(1);
const pageSize1 = ref(10);
const pageSize2 = ref(10);
const totalItems1 = ref(0);
const totalItems2 = ref(5);
const productList = ref([]);
const workReportList = ref([]);
const allDictionaries = ref({}); // To store all dictionary data

// Define the dictionary keys for product status, type, and company
const dictionaryKeysToFetch = ['Ware_ProductState', 'Productgui', 'Ware_ProductCompany'];

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  taskInfo: {
    type: Object,
    default: () => ({})
  }
});

// 定义emit
const emit = defineEmits(['update:visible']);

// 方法
const handleClose = () => {
  console.log('Dialog closing...');
  emit('update:visible', false);
};

const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
};

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
};

const getTableStructure = async () => {
  try {
    // 尝试获取表结构
    const response = await http.get('http://localhost:9991/api/ReportWorkRecord/GetPageData');
    console.log('表结构响应:', response);
    return response;
  } catch (error) {
    console.error('获取表结构失败:', error);
    return null;
  }
};

// 添加一个测试不同报工数据格式的函数
const testReportWorkFormats = async () => {
  try {
    if (!props.taskInfo.ProcessTaskId) {
      console.error('缺少工序任务ID');
      return;
    }
    
    // 测试不同的数据格式
    const testFormats = [
      // 格式1：只有ProcessTaskId
      {
        mainData: {
          ProcessTaskId: props.taskInfo.ProcessTaskId
        },
        detailData: [],
        delKeys: null
      },
      // 格式2：使用小写processTaskId
      {
        mainData: {
          processTaskId: props.taskInfo.ProcessTaskId
        },
        detailData: [],
        delKeys: null
      },
      // 格式3：使用taskId
      {
        mainData: {
          TaskId: props.taskInfo.ProcessTaskId
        },
        detailData: [],
        delKeys: null
      },
      // 格式4：使用完整仓库单据格式
      {
        mainData: {
          ProcessTaskId: props.taskInfo.ProcessTaskId,
          WareHouseBillCode: "",
          WareHouseBillType: "common",
          WareHouseDate: "2025-06-20 00:00:00",
          Remark: "测试报工"
        },
        detailData: [],
        delKeys: null
      }
    ];
    
    console.log('将测试以下格式:', testFormats);
    
    // 在生产环境中，您可能需要循环测试这些格式
    // 但为了避免多次API调用，这里我们只是记录这些格式
    
    return testFormats;
  } catch (error) {
    console.error('测试格式准备失败:', error);
    return null;
  }
};

const startWork = async () => {
  try {
    // 确保有产品数据
    if (productList.value.length === 0) {
      ElMessage.warning('没有可用的产品信息');
      return;
    }

    const productInfo = productList.value[0]; // 获取第一个产品信息
    
    // 检查ProcessTaskId是否存在
    if (!props.taskInfo.ProcessTaskId) {
      ElMessage.error('缺少工序任务ID，无法报工');
      console.error('工序任务信息:', props.taskInfo);
      return;
    }
    
    // 准备测试格式
    await testReportWorkFormats();
    
    // 使用最简单的格式，只包含ProcessTaskId
    const reportData = {
      mainData: {
        // ReportWorkRecordId:"",
        ProcessTaskId: props.taskInfo.ProcessTaskId,
        CreateDate: new Date().toISOString(),
      ProductionWorkOrderId: "27817647-F0B1-4146-8906-3B8F13EBB7FA",
      ProductId: productInfo.productId || '', 
      ProductCode: productInfo.productCode || '', 
      ProductName: productInfo.productName || '', 
      ReportworkNum: 1, 
      ProcessesName: props.taskInfo.processName || '', 
      ProductType: productInfo.productType.toString() || '',
      ProductCompany: productInfo.productCompany || ''
      },
      detailData: [],
      delKeys: null
    };

    console.log('使用最简单的报工数据:', reportData);
    
    const response = await http.post('http://localhost:9991/api/ReportWorkRecord/Add', reportData);
    console.log('报工响应:', response);
    
    if (response && response.status === true) {
      ElMessage.success('报工记录添加成功！');
    } else {
      ElMessage.error('报工记录添加失败: ' + (response ? response.message : '未知错误'));
      console.error('错误详情:', response);
      
      // 建议联系后端开发人员
      console.warn('建议联系后端开发人员，获取正确的API请求格式');
    }
  } catch (error) {
    ElMessage.error('报工记录添加失败');
    console.error('添加报工记录失败:', error);
  }
  handleClose();
};

const getProductInfo = async () => {
  try {
    const responseData = await http.get(`http://localhost:9991/api/ProcessTask/getProductInfoByTaskIdAsync?taskId=${props.taskInfo.ProcessTaskId}`);
    
    console.log('获取产品信息响应:', responseData);
    
    if (responseData) {
      const productData = {
        productId: responseData.productId || '',
        productCode: responseData.productCode || '',
        productName: responseData.productName || '',
        productType: responseData.productType || '', 
        productCompany: responseData.productCompany || '', 
        specification: '-', 
        unit: '-', 
        productBatch: responseData.productBatch || '', 
        productNumS: responseData.productNumS || 0, 
        productNumX: responseData.productNumX || 0, 
        planQuantity: responseData.productNums || 0,
        completedQuantity: responseData.productSave || 0,
        defectQuantity: 0, 
        status: responseData.productState || '' 
      };
      productList.value = [productData];
      totalItems1.value = productList.value.length;
    } else {
      ElMessage.error('获取成品信息失败: 数据为空');
      productList.value = [];
      totalItems1.value = 0;
    }
  } catch (error) {
    ElMessage.error('获取成品信息失败');
    console.error('获取成品信息失败:', error);
    productList.value = [];
    totalItems1.value = 0;
  }
};

const getDictionaryText = (dictionaryKey, value) => {
  const dict = allDictionaries.value[dictionaryKey];
  if (dict) {
    const found = dict.find(item => item.value == value);
    return found ? found.text : value; 
  }
  return value; 
};

const getStatusType = (status) => {
  const statusMap = {
    '1': 'info', 
    '2': 'warning', 
    '3': 'success', 
    '4': 'danger' 
  };
  return statusMap[status] || 'info';
};

// Fetch all dictionary data on component mount
onMounted(async () => {
  try {
    const responseData = await http.post('/api/Sys_Dictionary/GetVueDictionary', dictionaryKeysToFetch);
    
    // 确保 responseData 是一个数组，并将其转换为 { dicNo: data } 的对象格式
    if (responseData && Array.isArray(responseData)) {
      const transformedDict = {};
      responseData.forEach(dictItem => {
        if (dictItem.dicNo && Array.isArray(dictItem.data)) {
          transformedDict[dictItem.dicNo] = dictItem.data;
        }
      });
      allDictionaries.value = transformedDict;
      console.log('字典数据加载成功:', allDictionaries.value);
    } else {
      console.error('获取字典数据失败或数据为空: 响应数据格式不正确', '完整响应:', responseData);
    }
  } catch (error) {
    console.error('获取字典数据失败:', error);
  }
});

// 监听props变化
watch(() => props.visible, (newVal) => {
  console.log('Dialog visible prop changed to:', newVal);
  if (newVal && props.taskInfo.ProcessTaskId) {
    getProductInfo();
  }
});

watch(() => props.taskInfo, (newVal) => {
  console.log('Task info changed:', newVal);
}, { deep: true });
</script>

<style scoped>
.execution-plan-container {
  padding: 10px;
}

.plan-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.sub-section-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 15px;
  padding: 8px;
  background-color: #f8f8f8;
}

.info-section {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding-bottom: 15px;
}

.info-grid {
  display: flex;
  flex-direction: column;
  padding: 0 15px;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-item {
  flex: 1;
  display: flex;
}

.info-label {
  font-weight: bold;
  min-width: 100px;
}

.process-flow {
  padding: 0 15px;
  margin-top: 20px;
}

.flow-title {
  margin-bottom: 15px;
}

.flow-steps {
  display: flex;
  align-items: center;
}

.flow-step {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.step-circle {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #dcdfe6;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  margin-bottom: 8px;
}

.flow-step.active .step-circle {
  background-color: #409eff;
}

.flow-line {
  flex: 1;
  height: 2px;
  background-color: #dcdfe6;
  margin: 0 10px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}
</style> 